package cn.efunbox.afw.core.entity;


import cn.efunbox.afw.core.exception.ApiException;

import java.io.Serializable;
import java.util.Map;

/**
 * @author tomas
 * @date 2015-07-06
 * @what api 返回结果集
 */
public class ApiResult<T> implements Serializable {

  private static final long serialVersionUID = 1L;

  private boolean success = true;

  private int code;//状态码 非200 都是错误

  private String  message;//错误信息

  private T data;//结果数据

  public ApiResult() {
  }

  public ApiResult(ApiCode apiCode) {
    this(apiCode.getCode(), apiCode.getMessage());
  }


  private ApiResult(int code, String message) {
    this.code = code;
    if(code!=200){
      this.success=false;
    }
    this.message = message;
  }

  private ApiResult(ApiCode apiCode, T data) {
    this(apiCode.getCode(), apiCode.getMessage());
    this.data = data;
  }

  public static ApiResult ok() {
    return new ApiResult(ApiCode.OK);
  }

  public static ApiResult ok(Object value) {
    return new ApiResult(ApiCode.OK, value);
  }

  public static ApiResult ok(String name, Object value) {
    return new ApiResult(ApiCode.OK, Maper.of(name, value));
  }

  public static ApiResult ok(Map<String, Object> data) {
    return new ApiResult(ApiCode.OK, data);
  }

  public static ApiResult error(ApiException exception) {
    return new ApiResult(Integer.parseInt(exception.getCode()),exception.getMessage());
  }

  public static ApiResult error(ApiCode code) {
    return new ApiResult(code);
  }

  public static ApiResult error(ApiCode code, Object value) {
    return new ApiResult(code, value);
  }

  public static ApiResult error(ApiCode code, String name, Object value) {
    return new ApiResult(code, Maper.of(name, value));
  }

  public static ApiResult error(ApiCode code, Map<String, Object> data) {
    return new ApiResult(code, data);
  }

  public boolean getSuccess() {
    return success;
  }

  public void setSuccess(boolean success) {
    this.success = success;
  }

  public int getCode() {
    return code;
  }

  public void setCode(int code) {
    this.code = code;
  }

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public T getData() {
    return data;
  }

  public void setData(T data) {
    this.data = data;
  }
}
